﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace Itk.Fields
{
    public class OrderField : SPFieldNumber
    {
        public OrderField(SPFieldCollection fields, string fieldName) : base(fields, fieldName) { }
        public OrderField(SPFieldCollection fields, string typeName, string displayName) : base(fields, typeName, displayName) { }

        //Returns a field control for the page
        public override BaseFieldControl FieldRenderingControl
        {
            get
            {
                BaseFieldControl oControl = new OrderFieldControl { FieldName = InternalName };
                return oControl;
            }
        }

        //Performs all validation before the field value is stored
        public override String GetValidatedString(object value)
        {
            if (Required && (value == null || string.IsNullOrEmpty(value.ToString())))
                throw new SPFieldValidationException(SPResource.GetString(Strings.MissingRequiredField));

            int v;
            bool bIsInt = int.TryParse(value.ToString(), out v);
            if (!bIsInt)
                throw new SPFieldValidationException(SPResource.GetString(Strings.ValidationFieldValidationFailed));

            return value.ToString();
        }

        public override void OnAdded(SPAddFieldOptions op)
        {
            Indexed = true; //The column MUST be indexed to eliminate potential threshold issues
            Required = true;
            Update();

            base.OnAdded(op);
        }
    }
}
